package com.lzh.runke.caogao;

import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;

/**
 * @Description: 反射
 * @Author: LiuZiHao
 * @Date: 2022/8/2 16:20
 */
public class Test3 {
    public static void main(String[] args) {
        Student build = Student.builder().id("1").name("test1").i100Test("test2").build();
        String i100Test = getFieldValueByFieldName("i100Test", build);
        System.out.println("i100Test = " + i100Test);

        System.out.println("" + "01");
    }

    /**
     * 按属性名称获取实例化对象的属性值
     *
     * @param fieldName
     * @param object
     * @return
     */
    private static String getFieldValueByFieldName(String fieldName, Object object) {
        try {
            Field field = object.getClass().getDeclaredField(fieldName);
            //对private的属性的访问
            ReflectionUtils.makeAccessible(field);
            return (String) field.get(object);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
